package display;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;

import model.Tour;

import datencontext.Datencontext;

import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import helper.DisplayHelper;

public class LoginDisplay extends JPanel {
	private JTextField textField;
	private JPasswordField passwordField;
	private JFrame jframe;
	private Integer counterFehlgeschlageneAnmeldeversuche = 0;
	private Integer MAXIMALEABMELDEVERSUCHE = 4;
	

	/**
	 * Create the panel.
	 */
	public LoginDisplay(final JFrame jframe) {
		this.jframe = jframe;
		setLayout(null);
		final JButton btnOk = new JButton("Anmelden");
		JLabel lblBenutzer = new JLabel("Benutzer:");
		lblBenutzer.setBounds(90, 58, 60, 25);
		add(lblBenutzer);

		JLabel lblPasswort = new JLabel("Passwort:");
		lblPasswort.setBounds(90, 94, 60, 25);
		add(lblPasswort);

		textField = new JTextField();
		textField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				btnOk.setEnabled(DisplayHelper.IstTextNichtLeer(passwordField
						.getPassword())
						&& DisplayHelper.IstTextNichtLeer(textField.getText()));
			}
		});
		lblBenutzer.setLabelFor(textField);
		textField.setBounds(160, 60, 120, 25);
		add(textField);
		textField.setColumns(10);

		passwordField = new JPasswordField();
		passwordField.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				btnOk.setEnabled(DisplayHelper.IstTextNichtLeer(passwordField
						.getPassword())
						&& DisplayHelper.IstTextNichtLeer(textField.getText()));
			}
		});
		lblPasswort.setLabelFor(passwordField);
		passwordField.setBounds(160, 96, 120, 25);
		add(passwordField);

		btnOk.setEnabled(false);
		btnOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (Datencontext.isUserValidate(textField.getText(),
						passwordField.getPassword())) {
					Tour tour = Datencontext.LadeDummyTourdaten();
					jframe.getContentPane().removeAll();
					jframe.getContentPane().add(new StreetViewDisplay(jframe, tour), BorderLayout.CENTER);
					jframe.getContentPane().validate();
				}
				else
				{
					counterFehlgeschlageneAnmeldeversuche++;
					if(counterFehlgeschlageneAnmeldeversuche == MAXIMALEABMELDEVERSUCHE)
					{
						jframe.getContentPane().removeAll();
						jframe.getContentPane().add(new LoginDisplayFailed(), BorderLayout.CENTER);
						jframe.getContentPane().validate();
					}
				}

			}
		});
		btnOk.setBounds(160, 132, 120, 25);
		add(btnOk);

	}
}
